package com.wk.utils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class StringUtilsSub {
    //按照中文长度截取字符串
    public static String subStringLength(String msg,int limit){
        
        if(msg!=null&&msg.getBytes(Charset.forName("GBK")).length>limit){
            int length=0;
           for (int i=0;i<msg.length();i++){
               if(isChineseChar(msg.charAt(i))){
                   length+=2;
               }else {
                   length++;
               }
               if (length>limit){
                   msg=msg.substring(0,i);
                   break;
               }
           }
        }
        return msg;
    }

    private static boolean isChineseChar(char c) {
        if(c>='\u4E00'&&c<='\u9FA5'||c>='\uE815'&&c<='\uE864'){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String nihao = subStringLength("你nihao", 4);
        System.out.println("nihao = " + nihao);
    }
}
